package com.notes.romania.broadcastreceiver;

import java.io.IOException;
import java.util.Calendar;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.PowerManager;
import android.os.PowerManager.WakeLock;
import android.widget.Toast;

import com.notes.romania.NotificationReceiver;
import com.notes.romania.R;
import com.notes.romania.reminder.RemManager;
import com.notes.romania.reminder.Reminder;

public class AlarmBroadcastReceiver extends BroadcastReceiver{
	private static MediaPlayer mediaPlayer;
	
	@Override
	public void onReceive(Context context, Intent intent) {
		SharedPreferences settings = context.getSharedPreferences(RemManager.PREFS_NAME, Context.MODE_PRIVATE);
    	SharedPreferences.Editor editor = settings.edit();
    	
    	RemManager.setUp(settings,  editor);
    	
		lookForReminders(context);
	}
	
	private void lookForReminders(Context context){	
		//Get Calendar
		Calendar c = Calendar.getInstance();
		
		//Reminder
		Reminder rem = null;
		int remInMemory = RemManager.getListSize(), i;
		
		//Get a list with reminders id
		int ids[] = new int[remInMemory + 1];
		for(i = 1; i <= remInMemory; i ++)
			ids[i] = RemManager.getIdAtIndex(i);
			
		for(i = 1; i <= remInMemory; i ++){
			rem = RemManager.readRem(ids[i]);
			//Check whether reminder "rem" has the current date as currentDate
			if(
					c.get(Calendar.YEAR) == rem.year &&
					c.get(Calendar.MONTH) == rem.month &&
					c.get(Calendar.DAY_OF_MONTH) == rem.day &&
					c.get(Calendar.HOUR_OF_DAY) == rem.hour &&
					c.get(Calendar.MINUTE) == rem.minute){
				wakePhone(context);
				playSound(context, rem);
				createNotification(context, rem);
				
				RemManager.removeRem(rem);
				
				if(rem.repeat){	//We must add it again in memory but at currentTime + interval
					c.add(Calendar.YEAR, rem.yearsDelay);
					c.add(Calendar.DAY_OF_YEAR, rem.yearsDelay);
					c.add(Calendar.HOUR_OF_DAY, rem.hoursDelay);
					c.add(Calendar.MINUTE, rem.minutesDelay);
					
					//Retrieve date
					rem.year = c.get(Calendar.YEAR);
					rem.month = c.get(Calendar.MONTH);
					rem.day = c.get(Calendar.DAY_OF_MONTH);
					rem.hour = c.get(Calendar.HOUR_OF_DAY);
					rem.minute = c.get(Calendar.MINUTE);
					
					//Save the new  reminder
					RemManager.putRem(rem);
					
					//Instantiate a new calendar because we've changed this one
					c = Calendar.getInstance();
				}
			}
		}
	}
	
	
	
	private void createNotification(Context context, Reminder rem) {
		String titleBar, title, message;
		titleBar = "New reminder: " + rem.text;
		title = rem.day + "/" + (rem.month + 1) + "/" + rem.year + " " + rem.hour + ":" + rem.minute;
		message = rem.text;
 		NotificationManager notificationManager = (NotificationManager) 
 					context.getSystemService(Context.NOTIFICATION_SERVICE);
 		Notification notification = new Notification(R.drawable.ic_launcher,
 				titleBar, System.currentTimeMillis());
 		// Hide the notification after its selected
 		notification.flags |= Notification.FLAG_AUTO_CANCEL;

 		Intent intent = new Intent(context.getApplicationContext(), NotificationReceiver.class);
 		intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 
 		
 		intent.putExtra("id", rem.id);
 		
 		intent.putExtra("year", rem.year);
 		intent.putExtra("month", rem.month);
 		intent.putExtra("day", rem.day);
 		intent.putExtra("hour", rem.hour);
 		intent.putExtra("minute", rem.minute);

 		intent.putExtra("repeat", rem.repeat);
 		
 		intent.putExtra("yearsDelay", rem.yearsDelay);
 		intent.putExtra("daysDelay", rem.daysDelay);
 		intent.putExtra("hoursDelay", rem.hoursDelay);
 		intent.putExtra("minutesDelay", rem.minutesDelay);
 		
 		intent.putExtra("defaultSound", rem.defaultSound);
 		intent.putExtra("soundPath", rem.soundPath);
 		
 		intent.putExtra("text", rem.text);
 		
 		PendingIntent activity = PendingIntent.getActivity(context.getApplicationContext(), 0, intent,
 				Intent.FLAG_ACTIVITY_MULTIPLE_TASK);
 		
 		notification.setLatestEventInfo(context.getApplicationContext(), title,
 				message, activity);
 		notification.number += 1;
 		notificationManager.notify(rem.id, notification);
 	}
	
	
	private void wakePhone(Context context){
 		WakeLock wl;
 		PowerManager pm;
 		pm = (PowerManager)context.getSystemService(Context.POWER_SERVICE);
 		if(!pm.isScreenOn()) {
            wl = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK|PowerManager.ACQUIRE_CAUSES_WAKEUP,"WakeLock");
            wl.acquire(7000);
        }
        else{
        	//Screen on - no need of wake lock
        }
 	}
	
 	public static void playSound(Context context, Reminder rem){
 		//Stop current sound
 		stopSound();
 		
 		if(rem.defaultSound == false){	//Custom sound
	 		mediaPlayer = new MediaPlayer();
	 		try {
	 			mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
				mediaPlayer.setDataSource(rem.soundPath);
				mediaPlayer.prepare();
			} catch (IllegalArgumentException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (SecurityException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IllegalStateException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
	 		mediaPlayer.start();
	 		
	 		Toast.makeText(context, rem.soundPath, Toast.LENGTH_LONG).show();
 		}
 		else{
	 		 try {
	 	        Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
	 	        Ringtone r = RingtoneManager.getRingtone(context.getApplicationContext(), notification);
	 	        r.play();
	 	    } catch (Exception e) {}
 		}
 		
 	}
 	
 	public static void stopSound(){
 		//First we release the player
		if(mediaPlayer != null){
			mediaPlayer.pause();
			mediaPlayer.stop();
			mediaPlayer.release();
			mediaPlayer = null;
		}
 	}
}
